package cn.icanci.loopstack.bvb.dal.mongo.mongo;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import cn.icanci.loopstack.bvb.dal.mongo.common.PageList;
import cn.icanci.loopstack.bvb.dal.mongo.daointerface.BuryingDAO;
import cn.icanci.loopstack.bvb.dal.mongo.dateobject.BuryingDO;

/**
 * @author icanci
 * @since 1.0 Created in 2023/08/19 18:00
 */
@Service("buryingDAO")
public class MongoBuryingDAO extends AbstractBaseDAO<BuryingDO> implements BuryingDAO {

    @Override
    public void insert(BuryingDO burying) {
        super.insert(burying);
        mongoTemplate.insert(burying, COLLECTION_NAME);
    }

    @Override
    public void update(BuryingDO burying) {
        super.update(burying);
        mongoTemplate.save(burying, COLLECTION_NAME);
    }

    @Override
    public List<BuryingDO> queryAll() {
        Criteria criteria = Criteria.where(BuryingColumn.ENV).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.find(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public PageList<BuryingDO> pageQuery(BuryingDO burying, int pageNum, int pageSize) {
        Criteria criteria = Criteria.where(BuryingColumn.ENV).is(DEFAULT_ENV);
        if (StringUtils.isNotBlank(burying.getSystemKey())) {
            // 不分区大小写查询，其中操作符"i"：表示不分区大小写
            criteria.and(BuryingColumn.SYSTEM_KEY).regex("^.*" + burying.getSystemKey() + ".*$", "i");
        }
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, BuryingColumn.CREATE_TIME));
        return pageQuery(query, COLLECTION_CLASS, pageSize, pageNum, COLLECTION_NAME);
    }

    @Override
    public BuryingDO queryOneById(String _id) {
        Criteria criteria = Criteria.where(BuryingColumn._ID).is(_id);
        criteria.and(BuryingColumn.ENV).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public void batchInsert(List<BuryingDO> buryingList) {
        super.batchInsert(buryingList);
        mongoTemplate.insert(buryingList, COLLECTION_NAME);
    }
}
